package com.changge.content.api.menu;

import com.changge.common.core.domain.response.OptionsVO;
import com.changge.common.core.domain.response.Result;
import com.changge.common.models.dto.system.menu.MenuDTO;
import com.changge.common.models.enums.system.log.OperateType;
import com.changge.common.models.query.system.menu.MenuQuery;
import com.changge.common.models.vo.system.menu.MenuVO;
import com.changge.common.models.vo.system.menu.route.RouterVO;
import com.changge.system.facade.annotation.OperationLog;
import com.changge.system.facade.service.menu.IMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 *
 * @author zhangrongkang
 * @since 2023/4/17
 */
@Tag(name = "菜单控制器")
@RestController
@RequestMapping("/admin/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @Operation(summary = "获取菜单")
    @GetMapping("/getRoutes")
    public Result<List<RouterVO>> getRoutes() {
        List<RouterVO> menus = menuService.getRoutes();
        return Result.ok(menus);
    }

    @Operation(summary = "获取菜单数据")
    @PostMapping("/list")
    public Result<List<MenuVO>> list(@RequestBody MenuQuery menuQuery) {
        return Result.ok(menuService.listMenu(menuQuery));
    }

    @Operation(summary = "获取指定菜单数据")
    @GetMapping("/getMenuById/{id}")
    public Result<MenuVO> getMenuById(@PathVariable Long id) {
        MenuVO menuVO = menuService.getMenuById(id);
        return Result.ok(menuVO);
    }

    @Operation(summary = "获取菜单选项")
    @GetMapping("/listMenuOptions")
    public Result<List<OptionsVO>> listMenuOptions() {
        return Result.ok(menuService.listMenuOptions());
    }

    @Operation(summary = "保存菜单信息")
    @PostMapping("/save")
    public Result<Boolean> save(@Validated @RequestBody MenuDTO menuDTO) {
        Boolean result = menuService.save(menuDTO);
        // 数据库更新成功后操作Redis
        menuService.clearMenuCache(result);
        return Result.ok(result);
    }

    @Operation(summary = "删除指定菜单")
    @DeleteMapping("/delete/{id}")
    @OperationLog(type = OperateType.DELETE)
    public Result<Boolean> delete(@PathVariable Long id) {
        // 删除指定菜单
        Boolean result = menuService.delete(id);
        // 如果删除成功则清除Redis中缓存的数据
        menuService.clearMenuCache(result);
        return Result.ok(result);
    }
}
